package com.atlin.project.config.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * socket 处理器
 */
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
    /**
     * 登录用户 session
     */
    private static Map<Long, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    /**
     * 建立连接
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 假设用户ID通过查询参数传递
        long userId = Long.parseLong(session.getUri().getQuery().split("=")[1]);
        userSessions.put(userId, session);
        log.info("ws 创建连接：{}", userId);
    }


    /**
     * 关闭连接
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 假设用户ID通过查询参数传递
        long userId = Long.parseLong(session.getUri().getQuery().split("=")[1]);
        userSessions.remove(userId);
        log.info("ws 关闭连接：{}", userId);
    }

    /**
     * 收消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    }

    /**
     * 发送消息
     *
     * @param userId
     * @param message
     * @throws IOException
     */
    public static void notifyUser(long userId, String message) throws IOException {
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
            log.info("ws sendMessage {} ---> {}", userId, message);
        } else {
            log.error("ws notifyUser failure，{} 不存在连接。", userId);
        }
    }
}
